package com.ctgu.computer.service.impl;

import com.ctgu.computer.common.UserLocalTread;
import com.ctgu.computer.domain.dto.PageQueryDTO;
import com.ctgu.computer.domain.dto.UserPageDTO;
import com.ctgu.computer.domain.po.UserInfo;
import com.ctgu.computer.domain.result.PageResult;
import com.ctgu.computer.domain.result.Result;
import com.ctgu.computer.mapper.UserMapper;
import com.ctgu.computer.service.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final FileStorageService fileStorageService;

    @Override
    public UserInfo getInfo() {
        Integer userId = UserLocalTread.getUserId();
        return userMapper.selectUserInfoById(userId);
    }

    @Override
    public UserInfo getById(Integer userId) {
        return userMapper.selectUserInfoById(userId);
    }

    @Override
    public void updateStatus(List<Integer> ids) {
        userMapper.updateStatusByIds(ids);
    }

    @Override
    public PageResult page(UserPageDTO userPageDTO) {
        PageHelper.startPage(userPageDTO.getPageIndex(), userPageDTO.getPageSize());
        Page<UserInfo> userInfos = userMapper.list(userPageDTO);
        return new PageResult(userInfos.getTotal(),userInfos.getResult());
    }

    @Override
    public void addImage(MultipartFile file) {
        Integer userId = UserLocalTread.getUserId();
        FileInfo upload = fileStorageService.of(file)
                .setSaveFilename(userId+"-"+ UUID.randomUUID()+".png")
                .upload();
        UserInfo newUserInfo = UserInfo.builder()
                .userId(userId)
                .image(upload.getUrl())
                .build();
        userMapper.update(newUserInfo);
    }

    @Override
    public void batchDelete(List<Integer> ids) {
        if(ids.isEmpty()){
            return;
        }
        userMapper.batchDelete(ids);
    }

}
